//
//  GIFDisplayViewController.swift
//  GifUsage
//
//  Created by han on 2020/12/30.
//  Copyright © 2020 Ting Han. All rights reserved.
//

import UIKit
import Photos

class GIFDisplayViewController: UIViewController {
    
    
    @IBOutlet weak var imageView: UIImageView!
    let activityIndicator = UIActivityIndicatorView(style: .large)
   
    var path: String?
    var images = [ImageModel]()
    var duration: TimeInterval = 0.3
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(activityIndicator)
        activityIndicator.center = CGPoint(x: view.frame.midX, y: view.frame.midY)
        generateGIF()
        displayGIF()
        saveGIF()
    }
    
    @IBAction func homeAction(_ sender: Any) {
        navigationController?.popToRootViewController(animated: true)
    }
   
    @IBAction func saveAction(_ sender: Any) {
        saveGIF()
    }
    
    func generateGIF()  {
        guard images.count > 0 else { return }
        activityIndicator.startAnimating()
        let values =  images.map { $0.image }
        guard let path = GIFTools.generateGIF(images: values, delayTime: duration) else { return }
        self.path = path
        self.activityIndicator.stopAnimating()
    }
    
    func displayGIF() {
        guard let path = path, let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else { return }
        imageView.animate(withGIFData: data)
    }
    
    func saveGIF() {
        guard let path = path else { return }
        activityIndicator.startAnimating()
        PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.creationRequestForAssetFromImage(atFileURL: URL(fileURLWithPath: path))
        }, completionHandler: {success, error in
            if !success { print("error creating asset: \(String(describing: error))") }
            DispatchQueue.main.async {
                self.activityIndicator.stopAnimating()
                showTips(self, success ? "保存成功" : "保存失败", success ? "" : "error creating asset: \(String(describing: error))")
            }
        })
    }
}
